<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="县乡村" prop="areaId">
        <el-tree-select
          v-model="queryParams.areaId"
          :data="areaTree"
          :props="defaultProps"
          check-strictly
          accordion
          expand-on-click-node
          default-expand-all
          class="!w-340px"
          placeholder="请选择村/社区"
        />
      </el-form-item>
      <el-form-item label="所属机构" prop="bankId">
        <el-tree-select
          v-model="queryParams.bankId"
          :data="deptTree"
          :props="defaultProps"
          check-strictly
          default-expand-all
          node-key="id"
          class="!w-240px"
          placeholder="请选择归属机构"
        />
      </el-form-item>
      <el-form-item label="行长姓名" prop="pbName">
        <el-input
          v-model="queryParams.pbName"
          placeholder="请输入行长姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-140px"
        />
      </el-form-item>
      <el-form-item label="行长职务" prop="position">
        <el-select
          v-model="queryParams.position"
          placeholder="请选择职务"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions('circ_position')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['circ:contact-public:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['circ:contact-public:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" align="center" prop="id" width="60"/>
      <el-table-column label="县乡村" align="center" prop="areaId"  width="400">
        <template #default="scope">
          {{ areaList.find((item) => item.id === scope.row.areaId)?.name }}
        </template>
      </el-table-column>
      <el-table-column label="机构名称" align="center" prop="bankId" width="150">
        <template #default="scope">
          {{ deptList.find((item) => item.id === scope.row.bankId)?.name }}
        </template>
      </el-table-column>
      <el-table-column label="行长姓名" align="center" prop="pbName" width="150"/>
      <el-table-column label="行长职务" align="center" prop="position" width="150">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CIRC_POSITION" :value="scope.row.position" />
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center" prop="mobile" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['circ:contact-public:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['circ:contact-public:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ContactPublicForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import {DICT_TYPE, getIntDictOptions} from '@/utils/dict'
import {dateFormatter} from '@/utils/formatTime'
import download from '@/utils/download'
import {ContactPublicApi, ContactPublicVO} from '@/api/circ/contactpublic'
import ContactPublicForm from './ContactPublicForm.vue'
import {AreaApi, AreaVO} from '@/api/circ/area'
import {defaultProps, handleTree} from "@/utils/tree";
import * as DeptApi from "@/api/system/dept";
import {DeptVO} from "@/api/system/dept";

/** 联系人公示，用于联系人公示、银行数据统计功能模块 列表 */
defineOptions({ name: 'ContactPublic' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ContactPublicVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  areaId: undefined,
  bankId: undefined,
  pbName: undefined,
  position: undefined,
  mobile: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const areaTree = ref<Tree[]>([]) // 定义县乡村树形结构变量
const areaList = ref<AreaVO[]>([]) // 定义县乡村树形结构变量

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ContactPublicApi.getContactPublicPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
  // 【加载县乡村树】
  await getAreaTree()
}

/** 获取区域标签文本 */
const getAreaLabel = (areaId) => {
  if (!areaId || !areaTree.value) return ''

  const findLabel = (nodes) => {
    for (const node of nodes) {
      if (node.id === areaId) {
        return node.name
      }
      if (node.children) {
        const found = findLabel(node.children)
        if (found) return found
      }
    }
    return null
  }

  return findLabel(areaTree.value)
}

/** 获得县乡村树 */
const getAreaTree = async () => {
  areaTree.value = []
  const data = await AreaApi.getAreaList('')
  areaList.value = data
  // 组装树形结构数据，并为根节点添加一个空的 children 数组, 县/乡/村层级结构
  const root: Tree = { id: 0, name: '顶级县乡村', children: [] }
  root.children = handleTree(data, 'id', 'parentId')
  areaTree.value.push(root)
}


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ContactPublicApi.deleteContactPublic(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ContactPublicApi.exportContactPublic(queryParams)
    download.excel(data, '联系人公示，用于联系人公示、银行数据统计功能模块.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
const deptList = ref<DeptVO[]>([])
const deptTree = ref<Tree[]>([]) // 树形结构
onMounted(async () => {
  await getList()
  // 加载部门列表
  const deptParams = reactive()
  deptList.value = await DeptApi.getSimpleDeptListAppApi(deptParams)
  //console.log(deptList.value)
  // 部门树有层级
  deptTree.value = handleTree(deptList.value)
  })

</script>

